package utils;

import com.mysql.jdbc.Statement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Stack;

/**
 * @author tongchen
 * @create 2022-12-27 12:08
 */
public class DBUtils {
    //定义数据源
    public static DataSource dataSource;
   private static String url="jdbc:mysql://localhost:3307/exer2?characterEncoding=utf8&useSSL=false";
   private static String root="root";
    private  static String password="abc123";
    private DBUtils(){

    };//定义私有的构造方法（单例）
    static {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL(url);
        mysqlDataSource.setUser(root);
        mysqlDataSource.setPassword(password);
        dataSource=mysqlDataSource;
    }
    //获取连接对象
    public static Connection getConnection() throws SQLException {
      return dataSource.getConnection();
    }
    //关闭资源
    public static void closeResources(Connection connection , PreparedStatement statement, ResultSet resultSet)  {
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
